import React, { Component } from 'react';
import { NavBar, Icon, ListView } from 'antd-mobile';
import axios from 'axios'
import style from './index.module.scss'
import './index.module.scss'

class Com extends Component {
  constructor (props) {
    super(props)
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
  });
    this.state={
      travellist: {},
      travelid: null,
      author: {},
      answer: [],
      loves: [],
      col: false,
      dataSource,
            datas:[],
            pageIndex:1,
            isLoading: true,
            useBodyScroll: false,
            dataBlobs: {},
            sectionIDs:[],
            rowIDs:[],
            dataArr:[]
    }
  }

  genData(ref=false) {
    //获取数据
    let that=this;
    axios.get(`http://rap2.taobao.org:38080/app/mock/244731/api/traveldetail?travelid=${this.state.travelid}`).then(function (res){
        if(res.data.code==='200')
        {
            const lg = res.data.data.answer.length;
            // console.log(lg)
            let dataArr = that.state.dataArr;//关键代码
            let m=that.state.datas;
            for (let i = 0; i < lg; i++) {
                //每一次读取的数据都进行保存一次
                dataArr.push(`row - ${(that.state.pageIndex * lg) + i}`);
                m.push(res.data.data.answer[i])
            }
            // console.log('1111',dataArr)
            // console.log('22222',m)
            if(ref){
                //这里表示刷新使用
                that.setState({
                    datas:res.data.data.answer,
                    pageIndex:that.state.pageIndex+1,
                    dataSource: that.state.dataSource.cloneWithRows(dataArr),
                    isLoading: false,
                    //保存数据进state
                    dataArr:dataArr
                });
            }else{
                //这里表示上拉加载更多
                that.rData = { ...that.rData, ...dataArr };
                console.log(that.rData)
                that.setState({
                    datas:m,
                    pageIndex:that.state.pageIndex+1,
                    dataSource: that.state.dataSource.cloneWithRows(that.rData),
                    isLoading: false,
                    //保存数据进state
                    dataArr:dataArr
                });
            }
        }
    });
}
  componentWillMount(){
    //console.log(this.props.location.travelid)//传递过来的所有参数
    // console.log(this.props.location.state.travelid)//val值
    const id = localStorage.getItem("id")
    // 从本地取得此用户id，然后与请求来的数据中的loves的数据去匹对，如果有则col是true表示关注，否则为未关注
    // 这里用col模拟了一下
    const col = localStorage.getItem("col") ? true : false
    this.setState({
      travelid: id,
      col: col
    })
}
  componentDidMount () {
    axios.get(`http://rap2.taobao.org:38080/app/mock/244731/api/traveldetail?travelid=${this.state.travelid}`).then(res=>{
      console.log(res)
      this.setState({
        travellist: res.data.data,
        author: res.data.data.author,
        answer: res.data.data.answer,
        loves:res.data.data.loves,
      })
    })

    this.genData(true);
  }

  onEndReached = (event) => {
    if (this.state.isLoading && !this.state.hasMore) {
        return;
    }
    this.setState({ isLoading: true,pageIndex:this.state.pageIndex+1 });
    let that=this;
    setTimeout(() => {
        that.genData(false);
    }, 1000);
}

  // 点击改变关注状态，如果之前是关注则要在数据库把此数据删除，之前是未关注则要向数据库添加此项数据
  changelike = () => {
    this.setState({
      col: !this.state.col
    })
  }
  render() {
    const separator = (sectionID, rowID) => (
      <div
          key={`${sectionID}-${rowID}`}
          style={{
              backgroundColor: '#F5F5F9',
              height: 8,
              borderTop: '1px solid #ECECED',
              borderBottom: '1px solid #ECECED',
          }}
      />
  );
  let index = this.state.datas.length - 1;
  const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
          index = this.state.datas.length - 1;
      }
      const obj = this.state.datas[index--];
      return (
          <div key={rowID}
               style={{
                   padding: '0 0.15rem',
                   backgroundColor: '#fff',
                   height:'auto',
                   display: 'flex',
                   alignItems:'center',
                   position: 'relative'
               }}
          >
              <img src={obj.avatar} alt="" style={{width: '0.38rem', height: '0.36rem', marginRight: '0.15rem'}}/>
              <div>
                  <p style={{width: '1.75rem'}}>{obj.username}</p>
                  <p className={style.answerDesc} style={{width: '1.82rem'}}>{obj.desc}</p>
              </div>
              <span className='iconfont icon-iconfontzhizuobiaozhun44' style={{
                fontSize: '0.18rem',
                position: 'absolute',
                right: '0.15rem',
                top: '0.18rem',
                color: '#00B145'
              }}></span>
              <span style={{
                fontSize: '0.15rem',
                position: 'absolute',
                right: '0.20rem',
                top: '0.36rem',
                color: '#00B145'}}>8</span>
          </div>
      );
  }

    return (
      <div className='box'>
        {/* 头部 */}
        <header className='header'>
          <NavBar
            mode="light"
            // icon={<Icon type={require('./../../left.svg')} />}
            icon={ <span className="iconfont icon-fanhui" style={{ fontSize: '0.23rem', color: '#00B145' }}></span>}
            onLeftClick={() => {
              this.props.history.go(-1)
            }}
            rightContent={[
              <Icon key="0" type="ellipsis" color='#00B145' style={{ marginRight: '0.13rem' }} />
            ]}
            >精选游记
          </NavBar>
        </header>
        <div className='content'>
          {/* 景点图像区域 */}
          <div>
            <img src={this.state.travellist.img} alt="" style={{ width:"100%",height: '1.6rem'}}/>
            <p style={{ padding: '0.1rem 0.2rem 0 0.15rem', fontSize: '0.14rem', fontWeight: 'bold',lineHeight: '0.21rem', color:'rgba(51,51,51,1)'}}>{this.state.travellist.desc}</p>
            { this.state.travellist.hot ? '' : <img style={{width: '0.49rem', height: '0.17rem', marginLeft: '0.15rem', marginBottom: '0.08rem'}} src='/images/jinghua.png' alt=''></img>}
          </div>
          {/* 作者区域 */}
          <div className={style.author}>
            {/* 发布作者头像 */}
            <div className={style.avatar}>
              <img src={this.state.author.avatar} alt=""/>
               <div>
                 <p>{this.state.author.name}</p>
                 <span>{this.state.author.pubdata}</span>
                </div>     
            </div>
            {/* 发布时间 */}
            <p style={{ fontSize: '0.12rem', opacity: 0.8, color: 'rgba(102,102,102,1)', width: '100%', textAlign: 'left', paddingLeft: '0.15rem', marginBottom: '0.1rem'}}>拍摄于{this.state.author.photodata}</p>
            {/* 点赞者 */}
            <div className={style.love}>
              <div>
              {
                this.state.loves.map((item,index)=>{
                  if(index<6){
                    return <img key={item.userid} src={item.avatar} alt=""/>
                  }
                  return false
                })
              }
              </div>
              {
                this.state.col ? <span className='iconfont icon-weibiaoti105' onClick={this.changelike} style={{ fontSize: '0.19rem',color: '#d81e06'}}>{this.state.loves.length > 99 ? '99+': this.state.loves.length}</span> :
                <span className='iconfont icon-Group-' onClick={this.changelike} style={{ fontSize: '0.19rem'}}>{this.state.loves.length > 99 ? '99+': this.state.loves.length}</span>
              }
            </div>
          </div>
          {/* 回复区域 */}
          <p style={{padding: '0 0 0.15rem 0.15rem',fontWeight:'bold',color:'rgba(51,51,51,1)' ,fontSize: '0.14rem'}}>回复</p>
          <div className={style.answer}>
            {/* 此处应为当前用户得头像 */}
            <img src={this.state.author.avatar} alt=""/>
            <input type="text" placeholder='写个回复，pick楼主'/>
            <span>摇一句</span>
          </div>
          <ListView
                key={this.state.useBodyScroll ? '0' : '1'}
                ref={el => this.lv = el}
                dataSource={this.state.dataSource}
                renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                    {this.state.isLoading ? 'Loading...' : 'Loaded'}
                </div>)}
                renderRow={row}
                renderSeparator={separator}
                useBodyScroll
                style={this.state.useBodyScroll ? {} : {
                    border: '1px solid #ddd',
                    margin: '5px 0'
                }}
                // pullToRefresh={<PullToRefresh
                //     refreshing={this.state.refreshing}
                //     onRefresh={this.onRefresh}
                // />}
                onEndReachedThreshold={1000}
                onEndReached={this.onEndReached}
                pageSize={5}
            />
        </div>
      </div>
    );
  }
}

export default Com
